
function Json2Uri(data) {
  try {
      var tempArr = [];
      for (var i in data) {
          var key = i;
          var value = encodeURIComponent(data[i]);
          if (value!=null && "null"!=value && "undefined"!=value && undefined!=value) {
            tempArr.push(key + '=' + value);
          }
       }
      var urlParamsStr = tempArr.join('&');
      return urlParamsStr;
  } catch (err) {
      return '';
  }
}   

/**
 * {url:请求地址,
 *  method:get/post
 *  params:json参数,
 *  data json传参
 * }
 */
const request=(data)=> {
  return new Promise(function(resolve, reject) {
    var app = getApp();

    var header = {}
    // console.log(app.globalData.token)
    header = {
      'Authorization': app.globalData.token
      // 'Authorization': 'BearereyJhbGciOiJIUzUxMiJ9.eyJtY2hJZCI6IjEwMjAwIiwibmlja25hbWUiOiLmiYvmnLrnlKjmiLc4OTciLCJleHAiOjE2MzE1MzQ4NDQsInVzZXJJZCI6ImMxZGY0ZTMwNTQ5MjRlNDViMWUzNzZmYThlZjk1NTJmIiwidXNlcm5hbWUiOiJtY2hfMTAyMDBfMTM5NTk2ODc4OTcifQ.vhvNaVQiSBYsaQixwA1QY3MDvKTsKqZ4Ch3Pjfc8vXpysadYVUwXTrMueXW8wpu2wFRAw6IqUmzD7GUQb4b5wQ'
    }
    // if (app.globalData.token!=null) {
    //    header = {
    //     'Authorization': app.globalData.token
    //   }
    // }
 
    var url = data.url;

    if (data.params!=null && data.params!=undefined) {
      var params = Json2Uri(data.params)
      if (url.indexOf('?')>=0) {
        url = url + '&' + params
      } else {
        url = url + '?' + params      
      }
    }

    wx.request({
      url: app.APP_BASE_API + url,
      header: header,
      method: data.method,
      data: data.data,
      success: function (res) {
        if (res.data.type=="error") {
          if (res.data.content!=null) {
            wx.showToast({title:res.data.content,icon:"none"})
          } else {
            wx.showToast({title:"请求错误..",icon:"none"})
          }
          reject(res.data);
        } else {
          resolve(res.data);
        }
      },
      fail: function (err) {
        wx.showToast({title:"请求错误..",icon:"none"})
        reject(err);
      }   
  });

});
}

export default request
